#include "QtUI/ExistingProjectListWidget.qth"
#include "QtUI/ExistingProjectListWidget.moh"
#include "QtUI/ConnectionListComboBox.qth"
#include "QtUI/DummyProjectBrowserWidget.qth"
#include "AbsUI/ProjectBrowserWidget.hpp"
#include "AbsUI/UIFactory.hpp"
#include <QtGui/QComboBox>
#include <QtGui/QListWidget>
#include <QtGui/QGridLayout>
#include <QtGui/QLabel>


namespace QtUI
{

ExistingProjectListWidget::ExistingProjectListWidget( 
		const Storage::ConnectionConfigCollection& rConnCfgColl, AbsUI::UIFactory& rUIFactory, QWidget* pParent /*= NULL*/)
	: QWidget( pParent)
	, rUIFactory_( rUIFactory)
	, pPrjBrowserWidget_( NULL)
{
	QGridLayout* pLayout = new QGridLayout;
	this->setLayout( pLayout);

	pConnectionSelector_ = new ConnectionListComboBox( rConnCfgColl);
	QLabel* pConnSelLabel = new QLabel;
	pConnSelLabel->setBuddy( pConnectionSelector_);
	pConnSelLabel->setText( tr( "Available connections"));
	pLayout->addWidget( pConnSelLabel, 0, 0);
	pLayout->addWidget( pConnectionSelector_, 0, 1);

	QLabel* pPrjBrowserLabel = new QLabel;
	pPrjBrowserLabel->setText( tr( "Available projects"));
	pLayout->addWidget( pPrjBrowserLabel, 1, 0, 1, 2);

	pConnectionSelector_->setCurrentIndex( 0);
	this->replaceProjectBrowser( 0);

	connect( pConnectionSelector_, SIGNAL( currentIndexChanged( int)), this, SLOT( replaceProjectBrowser( int)));
}

// ---------------------------------------------------------------------------------------------------------------------

void ExistingProjectListWidget::replaceProjectBrowser( int index)
{
	delete pPrjBrowserWidget_;
	const Storage::ConnectionConfig* pSelectedConnCfg = pConnectionSelector_->connConfig( index);
	if( NULL == pSelectedConnCfg)
	{
		pPrjBrowserWidget_ = new DummyProjectBrowserWidget( "");
	}
	else
	{
		try
		{
			pPrjBrowserWidget_ = rUIFactory_.createProjectBrowserWidget( *pSelectedConnCfg);
		}
		catch( std::exception& e)
		{
			pPrjBrowserWidget_ = new DummyProjectBrowserWidget( e.what());
		}
	}
	qobject_cast< QGridLayout*>( this->layout())->addWidget( dynamic_cast< QWidget*>( pPrjBrowserWidget_), 2, 0, 1, 2);
}

// ---------------------------------------------------------------------------------------------------------------------

const Storage::ConnectionConfig* ExistingProjectListWidget::selectedConnectionConfig() const
{
	return pConnectionSelector_->selectedConnConfig();
}

// ---------------------------------------------------------------------------------------------------------------------

boost::any ExistingProjectListWidget::selectedProjectID() const
{
	return pPrjBrowserWidget_->selectedProjectID();
}


} // namespace QtUI
